using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace Jabr.Logic.Exceptions.Handling
{
    class XMLExceptionHandler : AbstractExceptionHandler
    {
        XmlDocument m_xml;

        public XMLExceptionHandler(Form p_maf)
            : base(null, p_maf)
        {
            InitXml();
        }

        public XMLExceptionHandler(AbstractExceptionForm p_cef, Form p_maf)
            : base(p_cef, p_maf)
        {
            InitXml();
        }

        private void InitXml()
        {
            m_xml = new XmlDocument();
            m_xml.AppendChild(m_xml.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
            m_xml.AppendChild(m_xml.CreateElement("Report"));
        }
        private void GenXml(AbstractInfo ei, XmlElement node)
        {
            XmlElement xei = m_xml.CreateElement(ei.GetType().Name);
            node.AppendChild(xei);
            foreach (string i_key in ei.Properties.Keys)
            {
                XmlElement xp = m_xml.CreateElement(i_key);
                xp.InnerText = ei.Properties[i_key];
                xei.AppendChild(xp);
            }
            if (ei.Inner != null)
            {
                GenXml(ei.Inner, xei);
            }
        }
        private void SaveXml(string p_path)
        {
            m_xml.Normalize();
            m_xml.Save(p_path);
        }

        protected override string SaveError(ExceptionInfo p_ei)
        {
            GenXml(new SystemInfo(), m_xml.DocumentElement);
            GenXml(p_ei, m_xml.DocumentElement);
            DirectoryInfo ds = new DirectoryInfo(Application.StartupPath + "\\" + Jabr.Properties.Resources.ERROR_DIR);
            if (!ds.Exists)
            {
                ds.Create();
            }
            string ret = ds.FullName + "\\" + "Error_" + DateTime.Now.ToFileTime().ToString() + ".xml";
            SaveXml(ret);
            return ret;
        }
    }
}
